﻿package disjunction.extensions.input
{
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.EventDispatcher;
	import flash.display.Sprite;
	
	public class KeyboardManager extends Sprite
	{
		private var _keysDown:Object;
		
		public function KeyboardManager(keysDown:Object)
		{
			_keysDown = keysDown;
			//only start accepting input when there is a stage (non-blocking initialisation)
			addEventListener(Event.ADDED, onAddedToStageHandler, false, 0, true);
		}
		
		public function onAddedToStageHandler(e:Event):void
		{
			parent.stage.focus = this;
			parent.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler, false, 0, true);
			parent.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler, false, 0, true);
		}
		
		private function keyDownHandler(e:KeyboardEvent):void
		{
			updateKeysPressed(e.keyCode, true);	
		}
	
		private function keyUpHandler(e:KeyboardEvent):void
		{
			updateKeysPressed(e.keyCode, false);
		}
		
		private function updateKeysPressed(keyCode:int, keyIsDown:Boolean):void
		{
			_keysDown[keyCode] = keyIsDown;		
		}
	}
}